/**
 * 类名：Sim卡业务类
 * 备注：负责Sim卡管理业务逻辑。
 * 作者：rankin
 * 日期：2016/03/4
 */
var Page = require('../models/page');
var Log = require('../models/log');
var Fault = require('../models/fault');
var Box = require('../models/boxes');
var Buyer = require('../models/buyer');
var BoxBuyer = require('../models/box_buyer');
var Sim = require('../models/sim');

var async = require('async');

module.exports = {
    list: function (req, res) {
        var account = req.query.account;
        new Buyer().findAccountByAccount(account, function (err, doc) {
            var buyer_id = doc.buyer_id;
            new BoxBuyer().findIdsByBuyer(buyer_id, function (datas) {
                if (datas.length > 0) {
                    var boxes = [];
                    for (var i = 0; i < datas.length; i++) {
                        boxes.push(datas[i].box_id);
                    }
                    var options = {box_id: {$in: boxes}};
                    new Sim().findUserSimById(options, function (err, datas) {
                        var sims = [];
                        for (var i = 0; i < datas.length; i++) {
                            sims.push(datas[i].sim);
                        }
                        var page = new Page(req.query.num);
                        var obj = {
                            page: page,
                            search: {sim: {$in: sims}}
                        };
                        new Fault().findForPage(obj, function (err, count, pageCount, datas) {
                            if (err) {
                            }
                            var dates = [];
                            for (var i = 0; i < datas.length; i++) {
                                dates.push((datas[i].date).toFormat('YYYY-MM-DD HH24:MI:SS'));
                            }
                            page.pageCount = pageCount;
                            res.render('box/fault_list', {
                                datas: datas,
                                dates: dates,
                                page: page,
                                account: account
                            });
                        })
                    });

                } else {
                    req.flash('error', '您没有绑定Sim卡.');
                    return res.redirect('/user_system/main');
                }
            });
        });
    }
};

